package dao.impl;

import java.util.ArrayList;

import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import dao.IPanelDAO;
import entities.Panel;

public class PanelDAO implements IPanelDAO {

	HibernateBase hibernateBase;

	public PanelDAO() {
		hibernateBase = HibernateBase.getInstance();
	}

	@Override
	public void init() {
		hibernateBase.init();
	}

	@Override
	public void close() {
		hibernateBase.close();
	}

	@Override
	public boolean create(Panel panel) {

		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().persist(panel);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

	@Override
	public Panel getBy(String name) {
		String queryString = "SELECT p FROM Panel p WHERE name='" + name + "'";

		Panel panel = null;

		Query query = hibernateBase.getManager().createQuery(queryString);
		ArrayList<Panel> panels = (ArrayList<Panel>) query.getResultList();

		panel = panels.get(0);

		return panel;
	}

	@Override
	public boolean update(Panel panel) {
		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().merge(panel);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

	@Override
	public Panel getBy(long id) {
		Panel panel = hibernateBase.getManager().find(Panel.class, id);
		return panel;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Panel> getAll() {
		String queryString = "SELECT p FROM Panel p";

		Query query = hibernateBase.getManager().createQuery(queryString);
		ArrayList<Panel> panels = (ArrayList<Panel>) query.getResultList();

		return panels;
	}

}
